﻿using RayD.Core;
using RayD.App.SystemModule;
using System;

namespace RayD.WebApi.Models
{
    /// <summary>
    /// 参数合法性实体基类
    /// </summary>
    public class BaseModel
    {
        /// <summary>
        /// 应用接入Id
        /// </summary>
        public string appid { get; set; }
        /// <summary>
        /// 时间戳
        /// </summary>
        public string timestamp { get; set; }
        /// <summary>
        /// 随机字符串
        /// </summary>
        public string nonce { get; set; }
        /// <summary>
        /// 加密签名内容
        /// </summary>
        public string signature { get; set; }

        /// <summary>
        /// 数据安全校验
        /// </summary>
        /// <returns></returns>
        public virtual void CheckParameter()
        {
            //根据Appid获取AppSecret并校验
            var server = ServiceContainer.Current.GetInstance<AppConfigApp>();
            var AppConfigEntity = server.GetEntityByAppId(this.appid);
            if (!AppConfigEntity.IsEmpty())
            {
                //校验签名
                string[] ArrTmp = { AppConfigEntity.B_AppSecret, this.timestamp, this.nonce };
                Array.Sort(ArrTmp); //TODO: 正序
                string tmpStr = Md5Helper.Encrypt(string.Join("", ArrTmp), 32).ToLower();//TODO: MD5小写32位加密
                if (tmpStr == this.signature && this.timestamp.CheckNumber())
                {
                    //校验时间戳（1分钟内）
                    DateTime dtTime = CommonHelper.ConvertTimestamp(this.timestamp.ToDouble());
                    double minutes = DateTime.Now.ToCstTime().Subtract(dtTime).TotalMinutes;
                    if (minutes > 1 || minutes < -1)
                    {
                        throw new Exception("时间戳校验失败！");
                    }
                }
                else
                {
                    throw new Exception("签名校验失败！");
                }
            }
            else
            {
                throw new Exception("AppId校验失败！");
            }
        }
    }
}
